package cn.bone.netty3.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

/**
 * Created by superbone on 2016/9/22.
 */
public class EchoClient {

    public static void main(String[] args) throws Exception {
        new EchoClient().connect();
    }

    public void connect() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY,true)
                    .handler(new ClientChildHander());
            //发起异步连接操作
            ChannelFuture f = b.connect("127.0.0.1",8000).sync();
            //等待客户端链路关闭
            f.channel().closeFuture().sync();
        } catch (Exception e){
            e.printStackTrace();
        }finally {
            group.shutdownGracefully();
        }
    }
}

class ClientChildHander extends ChannelInitializer<SocketChannel>{

    protected void initChannel(SocketChannel ch) throws Exception {

        //使用$_作为分隔符的自定义分隔符解码器
        ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
        ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,delimiter));

        //ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
        ch.pipeline().addLast(new StringDecoder());
        ch.pipeline().addLast(new EchoClientHandler());

    }
}

class EchoClientHandler extends ChannelHandlerAdapter{


    private int counter;
    private final String ECHO_REQ = "你好,欢迎使用DelimiterBaseFrameDecoder解码器$_";


    //连接成功之后执行的方法
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
       System.out.println("客户端消息:连接服务端成功!");
        for(int i=0;i<10;i++){
            ctx.writeAndFlush(Unpooled.copiedBuffer(ECHO_REQ.getBytes("UTF-8")));
        }
    }

    //发生异常时执行的方法
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("客户端消息:发生异常!");
        cause.printStackTrace();
        ctx.close();
    }

    //接收到数据时执行的方法
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try{
            System.out.println("客户端消息:接收到服务端发来的消息了"+(++counter)+"...");
            System.out.println((String)msg);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("-------------");
        }


    }


    //数据接收读取完毕后执行的方法
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端消息:读取服务端发来的消息完毕!");
    }
}
